package com.asimplefox.serurity;

import io.github.kloping.judge.Judge;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author github.kloping
 */
@Component
@Slf4j
public class TokenManager {

    public static final String ADMIN = "admin";
    public static final String VIP = "vip";

    public UserRoleDetails getContextUserDetail(HttpServletRequest request) {
        String token = getToken(request);
        if (Judge.isEmpty(token)) return null;
        UserRoleDetails urd = token2principal.get(token);
        if (urd != null) urd.test();
        return urd;
    }

    private String getToken(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        Object token = session.getAttribute("token");
        if (token == null || token.toString().isBlank()) {
            token = request.getHeader("token");
        }
        if (token == null || token.toString().isBlank()) {
            token = request.getHeader("authorization");
        }
        return token == null ? "" : token.toString();
    }

    /**
     * token 对应 用户登录
     */
    private final Map<String, UserRoleDetails> token2principal = new ConcurrentHashMap<>();
    /**
     * 用户名对应token 检测只能登录一个
     */
    private final Map<String, String> principal2token = new ConcurrentHashMap<>();

    public void set(String token, UserRoleDetails principal) {
        if (principal2token.containsKey(principal.getUsername())) {
            String oldToken = principal2token.get(principal.getUsername());
            token2principal.remove(oldToken);
        }
        token2principal.put(token, principal);
        principal2token.put(principal.getUsername(), token);
    }

    public boolean remove(String username) {
        String token = principal2token.remove(username);
        if (token != null) {
            return token2principal.remove(token) != null;
        }
        return false;
    }
}
